var islink = 2
$(function() {
	if ("WebSocket" in window) {
		webSocket(socketUrl,2);
		chatOnLoad();
	} else {
		console.log("您的浏览器不支持聊天!");
	}
	// 发送消息
	if ($('#send').length > 0) {
		$('#send').click(function() {
			if(socket && socket.readyState == 1){
				send();
			}else{
				webSocket(socketUrl,2);
				var timer = setInterval(function(){
					if(socket && socket.readyState == 1){
						clearInterval(timer);
						send();
					}
				},500);
				setTimeout(function(){
					if(timer){
						clearInterval(timer);
					}
				},10000);
			}
		});
	}
	// 发送简历
	if ($('#sendExpcet').length > 0) {
		$('#sendExpcet').click(function() {
			sendExpcet();
		});
	}
	// 发送职位
	if ($('#sendJob').length > 0) {
		$('#sendJob').click(function() {
			sendJob();
		});
	}
	// 发送职位
	if ($('#closeJob').length > 0) {
		$('#closeJob').click(function() {
			$('#joblist').addClass('none');
		});
	} 
	// 不感兴趣
	if ($('#nochat').length > 0) {
		$('#nochat').click(function() {
			nochat();
		});
	}
	if($('#send_content').length > 0){
		$('#send_content').on('keydown', function(e){
			var keyCode = e.keyCode;
			if(keyCode === 13){
				e.preventDefault();
				send();
			}
		});
	}
	// 查询准备数据
	if(toid !=''){
		getPrepare();
	}
	
	var pageTitle = document.title;
	var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' :  null;
	// 不同浏览器的事件名
	var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
	var onVisibilityChange = function(){
		if(newChatMsg && !document[hiddenProperty]){
			var titAn = true;
			clearInterval(titledsq);
			titledsq = setInterval(function(){
				if(titAn){
					document.title = '【新消息】';
					titAn = false;
				}else{
					document.title = $('#zwf').text();
					titAn = true;
				}
			},1000);
		}else{
			document.title = pageTitle;
			clearInterval(titledsq);
		}
	}
	document.addEventListener(visibilityChangeEvent, onVisibilityChange);
	
	// 列表未读消息
	if($('#showUnread').length > 0){
		$('#showUnread').click(function() {
			
			var list = $('#chatList').find('li');
			
			var i = $('#showUnread').find('i');
			if(i.hasClass('chat_wd_checkbox_xz')){
				i.removeClass('chat_wd_checkbox_xz');
				list.each(function(index,item){
					var su = $(this).find('.chat_box_usermsg').text();
					if($.trim(su)==''){
						$(this).removeClass('none');
					}
				})
			}else{
				i.addClass('chat_wd_checkbox_xz');
				list.each(function(index,item){
					var su = $(this).find('.chat_box_usermsg').text();
					if($.trim(su)==''){
						$(this).addClass('none');
					}
				})
			}
		});
	}
});
function webSocket(socketUrl,islink){
	var ping_timer = null;
		socket = new WebSocket(socketUrl);
		socket.onopen = function() {
			islink = 1;
			var ping = {
				type: 'ping'
			};
			ping_timer = setInterval(function() {
				if (socket && socket.readyState == 1){
					socket.send(JSON.stringify(ping));
				}else{
					socket.close();
				}
			}, 25000);
		};
			
		socket.onerror = function() {
			islink = 2;
			if(ping_timer){
				clearInterval(ping_timer);
			}
			/*
			layer.msg(chat_name+'服务器无法连接', 2, 8);
			*/
		};

		socket.onclose = function() {
			socket = null;
			if(ping_timer){
				clearInterval(ping_timer);
			}
			islink = window.localStorage.getItem("islink");
			if(islink == 1){
				webSocket(socketUrl,2);
				chatOnShow();
			}
		};
		//捕捉socket端发来的事件
		socket.onmessage = function(event) {
			var e = JSON.parse(event.data);
			switch (e.type) {
				//显示收到的消息
				case 'getMessage':
					getMessage(e.data);
					break;
				case 'getUnread':
					if ($('#memberNoChat').length > 0){
						getUnread();
					}
					break;
				case 'unsend':
					unSend(e.data);
					break;
				case 'error':
					islink = 2;
					break;
			}
		};
}
// 加载聊天数据
function chatOnLoad(){
	$.post(weburl + "/index.php?m=chat&c=goChat", {
		rand: Math.random()
	}, function(data) {
		if (data) {
			var res = JSON.parse(data);
			mine = res.mine;
			var t = setInterval(function(){
				if (socket && socket.readyState == 1){
					clearInterval(t);
					if(res.yuntoken && res.yuntoken.token){
						var yuntoken = res.yuntoken.token;
						var bind = {
							type: 'bind',
							data: {
								uid: mine.id,
								usertype: mine.usertype,
								yuntoken: yuntoken
							}
						}
						socket.send(JSON.stringify(bind));
						window.localStorage.setItem("islink", "1");
					}else{
						window.localStorage.setItem("islink", "2");
					}
				}
			},100);
			setTimeout(function(){
				if(t){
					clearInterval(t);
				}
			},10000);
			// 让其他页面检查未读消息
			if(toid !=''){
				setTimeout(function(){
					var jw = setInterval(function(){
						if (socket && socket.readyState == 1){
							clearInterval(jw);
							var message = {
								type: 'getUnread',
								data: {
									uid: mine.id,
								}
							}
							socket.send(JSON.stringify(message));
						}
					},100);
					setTimeout(function(){
						if(jw){
							clearInterval(jw);
						}
					},10000);
				},3000);
			}
		}
	});
}
// 重新连接请求数据
function chatOnShow(){
	$.post(weburl + "/index.php?m=chat&c=getToken", {
		rand: Math.random()
	}, function(data) {
		if (data) {
			var res = JSON.parse(data);
			var t = setInterval(function(){
				if (socket && socket.readyState == 1){
					clearInterval(t);
					if(res.yuntoken){
						var bind = {
							type: 'bind',
							data: {
								uid: mine.id,
								usertype: mine.usertype,
								yuntoken: res.yuntoken
							}
						}
						socket.send(JSON.stringify(bind));
						window.localStorage.setItem("islink", "1");
					}else{
						window.localStorage.setItem("islink", "2");
					}
				}
			},500);
			setTimeout(function(){
				if(t){
					clearInterval(t);
				}
			},10000);
		}
	})
}
function checkSend() {
	var content = document.getElementById('send_content').value;
	if (content.trim() != '') {
		$('#send').removeClass('disclick');
	} else {
		$('#send').addClass('disclick');
	}
}
function back(){
	history.back();
}
function getPrepare(){
	$.post(weburl + "/index.php?m=chat&c=prepare", {
		'toid': toid,
		'totype': totype
	}, function(data) {
		if (data) {
			var res = JSON.parse(data);
			var html = '',list = [];
			if(res.joblist){
				joblist = res.joblist;
				for(var i in joblist){
					list.push(i);
					html += '<div class="chatjob_list">';
					html +=	'<div class="chatjob_name">' + joblist[i].name + '</div>';
					html += '<div class="chatjob_xz">' + joblist[i].job_salary + '</div>';
					html += '<div class="chatjob_info">' + joblist[i].job_city_one;
					if(joblist[i].job_city_two){
						html += '-' + joblist[i].job_city_two;
					}
					if(joblist[i].job_exp){
						html += '<span class="chatjob_info_line">|</span>' + joblist[i].job_exp +'经验';
					}
					if(joblist[i].job_edu){
						html += '<span class="chatjob_info_line">|</span>' + joblist[i].job_edu+'学历';
					}
					html += '</div>';
					html += '<span class="chatjob_bth" data-jobid="'+ joblist[i].id +'" onclick="jobShow(this)">发送</span></div>';
				}
				if(list.length == 0){
					html = '<div class="chat_nojob">~ 亲 , 暂无可选职位哦！</div>';
				}
				$('#chatjob_list').html(html);
			}else{
				html = '<div class="chat_nojob">~ 亲 , 暂无可选职位哦！</div>';
				$('#chatjob_list').html(html);
			}
			if(res.expect){
				expect = res.expect;
				
				if($('#content_expect')){
					var ehtml = '<span class="chat_box_right_gtjob_n">期望职位</span><span class="chat_box_right_gtjob_name">'+ expect.name +'</span>';
					ehtml += '<span class="chat_box_right_gtjob_xz">'+ expect.salary +'</span>' + expect.city_classname + '<span class="chat_line">|</span>' + expect.exp_n;
					ehtml += '<span class="chat_line">|</span>' + expect.edu_n + '<a href="'+ expect.weburl +'" target="_blank" class="chat_box_right_gtjob_name">查看简历></a>';
					$('#content_expect').html(ehtml);
				}
				
				$('#eid').val(expect.id);
			}
			// 渲染聊天记录
			moreChat();
		}
	});
}
// 发送消息
function send() {
	var content = document.getElementById('send_content');
	if (content.value != '') {
		// 发送聊天
		if(toid != ''){
			sendMessage(content.value,'char','');
			content.value = '';
			checkSend();
		}else{
			layer.msg('请选择'+chat_name+'对象', 2, 8);
		}
	}
}
function getMessage(msg){
	if (msg.id && msg.totype == mine.usertype) {
		if(toid != '' && msg.id == toid){
			var html = chatRender(msg, 'get');
			// 收到消息处理
			setTimeout(function(){
				$.post(weburl + "/index.php?m=chat&c=setMsgStatus", {
					'id': toid,
					'type': totype,
					'nowid': mine.id,
					'nowtype': mine.usertype
				}, function(data) {
					if(data){
						var res = eval('(' + data + ')');
						if(res.errmsg){
							layer.msg(res.errmsg, 2,8,function(){
								location.href = weburl;
							});
						}
					}
				});
			},500);
		}else{
			// 聊天列表处理接收信息
			if ($('#chatList').length > 0){
				if ($('#chat_' + msg.id).length > 0){
					var msg_new = $('#chat_' + msg.id).find('.chat_box_usermsg');
					if(msg_new.text() == ''){
						$('#chat_' + msg.id).find('.chat_box_usermsg').text(1);
						$('#chat_' + msg.id).find('.chat_box_usertime').text(timeFormat(msg.timestamp));
					}else if(parseInt(msg_new.text()) > 0){
						var num = parseInt(msg_new.text()) + 1;
						$('#chat_' + msg.id).find('.chat_box_usermsg').text(num);
						$('#chat_' + msg.id).find('.chat_box_usertime').text(timeFormat(msg.timestamp));
					}
				} else {
					var html = '';
					html += '<li id="chat_'+msg.id+'" onclick="toChat('+msg.id+','+msg.ftype+','+msg.ftype+')">';
					html += '<div class="chat_box_userpic"><img src="'+msg.avatar+'" width="50" height="50"><i class="chat_box_usermsg">1</i></div>';
					html += '<div class="chat_box_userinfo"><div class="chat_box_username">'+msg.linkman+'<span class="chat_box_userzw">';
					
					if (msg.ftype=='1'){
						html += '求职者';
					}else{
						html += '招聘者';
					}
					html += '</span></div>';
					html += '<div class="chat_box_userp">';			
					if (msg.ftype =='1'){
						var content = msg.content;
						if(msg.msgtype == 'char'){
							if(content.indexOf('[img')){
								content = '图片消息';
							}
						}else{
							if(msg.msgtype == 'job'){
								content = '职位消息';
							}else if(msg.msgtype == 'resume'){
								content = '简历消息';
							}else if(msg.msgtype == 'change'){
								content = '面试消息';
							}
						}
						html += content;
					}else{
						html += msg.username;
					}				
					html += '</div><span class="chat_box_usertime">'+msg.timefromat+'</span></div></li>';
					$('#chatList').prepend(html);
				}
			}
			if ($('#memberNoChat').length > 0){
				if($('#memberHaveChat').hasClass('none')){
					$('#memberNoChat').addClass('none');
					$('#memberHaveChat').removeClass('none');
					$('#memberChatNum').text(1);
				}else{
					var num = $('#memberChatNum').text();
					if(parseInt(num) > 0){
						$('#memberChatNum').text(parseInt(num) + 1);
					}
				}
			}
		}
		newChatMsg = true;
		var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' :  null;
		if(!document[hiddenProperty]){
			var titAn = true;
			clearInterval(titledsq);
			titledsq = setInterval(function(){
				if(titAn){
					document.title = '【新消息】';
					titAn = false;
				}else{
					document.title = $('#zwf').text();
					titAn = true;
				}
			},1000);
		}
	}
}
// 由简历/职位详情页进入,发预定消息
function prepare() {
	var pdata = {};
	if (jid != '' && joblist && joblist[jid] && jobShowed){
		var html = '<li class="chat_li"><div class="chat_yx_job" data-wapurl="' + joblist[jid].weburl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_yx_job_name">' + joblist[jid].name + '</div>';
		html += '<span class="chat_yx_xz">' + joblist[jid].job_salary + '</span>';
		html += '<div class="chat_yx_com_name">' + joblist[jid].com_name + '</div>';
		html += '<div class="">' + joblist[jid].job_city_one;
		if(joblist[jid].job_city_two){
			html += '-' + joblist[jid].job_city_two;
		}
		if(joblist[jid].job_exp){
			html += ' . ' + joblist[jid].job_exp+'经验';
		}
		if(joblist[jid].job_edu){
			html +=  ' . ' + joblist[jid].job_edu+'学历';
		}
		html += '</div>';
		html += '<div class="chat_yx_time">' + timeFormat() + ' 由你发起的沟通</div></span></div></li>';
		// 发送消息
		sendMessage(html,'job',jid);
		
		setTimeout(function(){
			var send = '你好，可以聊聊吗？您这个职位我很感兴趣，希望进一步了解';
			sendMessage(send,'char','');
		},500);
	}
}

function sendExpcet() {
	if(expect){
		var html = '<li class="chat_li"><div class="chat_userresume" data-wapurl="' + expect.weburl + '" onclick="toShow(this)">';
			html += '<span><div class="chat_userresume_name">' + expect.uname + ' <span class="chat_userresume_ys">' + expect.sex_n +',' + expect.age + '岁</span></div>';
			html += '<div class="chat_userresume_info">' + expect.exp_n + ' . ' + expect.edu_n + ' </div>';
			html += '<div class="chat_userresume_want">期望职位 <span class="chat_userresume_wantjob">' + expect.name +'</span> </div>';
			html += '<div class="chat_userresume_pic"><img src=" ' + expect.photo + ' "></div></span></div></li>';
			// 发送消息内容
			sendMessage(html,'resume',expect.id);
	}else{
		var i = layer.confirm('您还没有可以投递的简历',
			{btn : ['前往发布','取消']},
			function(){
				window.location.href = weburl + '/member/index.php?c=expect&act=add';
				return false;
			},
			function(){
				layer.close(i);
			}
		);
	}
}

function toShow(obj){
	var url = obj.getAttribute('data-wapurl');
	if(url && url != ''){
		window.open(url);
	}
}

function sendInvite(id){
	var html = '<li class="chat_li"><div class="chat_sendcont">';
	html += '<div class="chat_sendcont_pic"><img src="' + mine.avatar + '"></div>';
	html += '<span class="chat_sendcont_p"><em class="chat_sendcont_yqbox">发送了面试邀请<i class="chat_sendcont_yq"></i></em></span></div></li>';
	// 发送消息
	sendMessage(html,'invite',id);
}
// 展示邀请详情
function inviteShow(obj){
	var id = obj.getAttribute('data-inviteid');
	if(id && id != ''){
		if(mine.usertype == 1){
			var url = weburl + '/member/index.php?index.php?c=invite';
		}else{
			var url = weburl + '/member/index.php?index.php?c=invite';
		}
		location.href = url;
	}
}

function sendJob() {
	$('#joblist').removeClass('none');
}

function jobShow(obj) {
	var id = obj.getAttribute('data-jobid');
	$('#joblist').addClass('none');
	if(jid != id && jid > 0){
		if (mine.usertype == 1) {
			var change = '您更换了与招聘者沟通的职位';
		} else {
			var change = '您更换了与求职者沟通的职位';
		}
		// 发送消息
		sendMessage(change,'change','');
	}
	
	var jobhtml = '<li class="chat_li"><div class="chat_yx_job" data-wapurl="' + joblist[id].weburl + '" onclick="toShow(this)">';
	jobhtml += '<span><div class="chat_yx_job_name">' + joblist[id].name + '</div>';
	jobhtml += '<span class="chat_yx_xz">' + joblist[id].job_salary + '</span>';
	jobhtml += '<div class="chat_yx_com_name">' + joblist[id].com_name + '</div>';
	jobhtml += '<div class="">' + joblist[id].job_city_one;
	if(joblist[id].job_city_two){
		jobhtml += '-' + joblist[id].job_city_two;
	}
	if(joblist[id].job_exp){
		jobhtml += ' . ' + joblist[id].job_exp+'经验';
	}
	if(joblist[id].job_edu){
		jobhtml += ' . ' + joblist[id].job_edu+'学历';
	}
	jobhtml += '</div>';
	if(jid != id  && jid > 0){
		jobhtml += '<div class="chat_yx_time">' + timeFormat() + ' 由你发起的沟通</div></span></div></li>';
	}
	// 发送消息
	sendMessage(jobhtml,'job',id);
	// 设置当前沟通职位
	jid = id;
}

function nochat() {
	layer.open({
		content: '设定不感兴趣将会删除与TA的'+chat_name+'记录，并将TA加入'+chat_name+'黑名单，确定继续？'
		,btn: ['确定', '取消']
		,yes: function(index){
			layer.close(index);
			var loading = layer.open({type: 2});
			$.post(weburl+"/index.php?m=chat&c=delChatLog", {to: toid, type: totype}, function (data) {
				layer.close(loading);
				if(data){
					var res = eval('(' + data + ')');
					if(res.errmsg){
						layer.msg(res.errmsg, 2,8,function(){
							location.href = weburl;
						});
					}else{
						window.history.back(-1);
					}
				}
			});
		}
	});
}
// 发送消息
function sendMessage(content, type, id){
	
	var time = new Date().getTime();
	if(socket && socket.readyState == 1){
		// 根据消息类型区分保存内容
		if(type == 'job'){
			var msgcontent = 'jobid=' + id;
			showChatJob(id);
		}else if(type == 'resume'){
			var msgcontent = 'eid=' + id;
		}else if(type == 'invite'){
			var msgcontent = 'inviteid=' + id;
		}else{
			var msgcontent = content;
		}
		var mineData = {
			id: mine.id,
			ftype: mine.usertype,
			avatar: mine.avatar,
			username: mine.username,
			linkman: mine.linkman,
			timestamp: new Date().getTime(),
			content: msgcontent,
			msgtype: type
		};

		var sendData = {
			mine: mineData,
			to: {
				id: toid,
				utype: totype
			}
		};
		var message = {
			type: 'chatMessage',
			data: {
				content: sendData
			}
		};
		// 保存聊天记录
		if(type != 'change'){
			var pdata = {
				to: sendData.to.id,
				totype: sendData.to.utype,
				content: msgcontent,
				timestamp: sendData.mine.timestamp,
				msgtype: sendData.mine.msgtype,
				nowid: sendData.mine.id,
				nowtype: sendData.mine.ftype
			};
			
			$.post(weburl+"/index.php?m=chat&c=chatLog", pdata, function (data) {
				if(data){
					var res = eval('(' + data + ')');
					if(res.error != 0){
						if(res.error == 3){
							layer.msg(res.errmsg, 2,8);
						}else if(res.errmsg){
							layer.msg(res.errmsg, 2,8,function(){
								location.href = weburl;
							});
						}
					}else{
						socket.send(JSON.stringify(message));
					}
				}
			});
		}else{
			socket.send(JSON.stringify(message));
		}
		// 消息时间间隔超60秒，显示新时间
		if(sendData.mine.timestamp - sendTime > 60*1000){
			$("#chat_content").find('ul').append('<li class="chat_li"><div class="chat_sendtime">' + timeFormat(sendData.mine.timestamp) + '</div></li>');
			sendTime = sendData.mine.timestamp;
		}
		// 渲染消息内容
		mineData.htmlcontent = content;
		var html = chatRender(mineData, 'send');
	}else{
		layer.msg(chat_name+'功能加载中', 2, 8);
	}
}
// 渲染消息内容
function chatRender(msg, type){
	if(type == 'send'){
		// 发送
		if(msg.msgtype == 'char'){
			var content = rexContent(msg.htmlcontent);
			// 我说
			var html  = '<li class="chat_li"><div class="chat_sendcont">';
				html += '<div class="chat_sendcont_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p">' + content + '</span></div></li>';
		}else if(msg.msgtype == 'change'){
			var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + msg.htmlcontent + '</span></div></li>';
		}else{
			var html = msg.htmlcontent;
		}
	}else {
		// 接收
		if(msg.msgtype == 'char'){
			msg.content = rexContent(msg.content);
			// 他说
			var html = '<li class="chat_li"><div class="chat_other_say">';
				html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p2">' + msg.content + '</span></div></li>';
		}else{
			if(msg.msgtype == 'job'){
				if(msg.content.indexOf('jobid') != -1){
					var jobid = msg.content.replace('jobid=','');
					var html = getJobHtml(jobid);
				}
			}else if(msg.msgtype == 'resume'){
				if(msg.content.indexOf('eid') != -1){
					var eid = msg.content.replace('eid=','');
					var html = getResumeHtml(eid);
				}
			}else if(msg.msgtype == 'change'){
				if (msg.ftype == 1) {
					var change = '求职者更换了与您沟通的职位';
				} else {
					var change = '招聘者更换了与您沟通的职位';
				}
				var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + change + '</span></div></li>';
			}else if(msg.msgtype == 'invite'){
				if(msg.content.indexOf('inviteid') != -1){
					var inviteid = msg.content.replace('inviteid=','');
					var html = '<li class="chat_li"><div class="chat_other_say" data-inviteid="' + inviteid + '" onclick="inviteShow(this)">';
					html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
					html += '<span class="chat_sendcont_p2"><em class="chat_sendcont_jsbox">发送了面试邀请<i class="chat_sendcont_jsyq"></i></em></span></div></li>';
				}
			}else{
				var html = msg.content;
			}
		}
		// 消息时间间隔超60秒，显示新时间
		if(msg.timestamp - sendTime > 60*1000){
			$("#chat_content").find('ul').append('<div class="chat_sendtime">' + timeFormat(msg.timestamp) + '</div>');
			sendTime = msg.timestamp;
		}
	}
	$("#chat_content").find('ul').append(html);
	var scroll = document.getElementById('chat_content').scrollHeight;
	chatScrollTo(scroll);
	// 图片类型加载较慢，滚动到底部需要时间
	if($("#chat_content").find('ul').last().find('img')){
		// 上面滚动过之后，新的高度
		lastscroll = document.getElementById('chat_content').scrollHeight;
		var timer = setInterval(function() {
			var imgscroll = document.getElementById('chat_content').scrollHeight;
			if(imgscroll > lastscroll){
				chatScrollTo(imgscroll);
				clearInterval(timer);
			}
		}, 200);
		setTimeout(function(){
			if(timer){
				clearInterval(timer);
			}
		},2000);
	}
	return html;
}
function getJobHtml(jobid, msg){
	var html = '';
	if(joblist && joblist[jobid]){
		html = '<li class="chat_li"><div class="chat_yx_job"  data-wapurl="' + joblist[jobid].weburl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_yx_job_name">' + joblist[jobid].name + '</div>';
		html += '<span class="chat_yx_xz">' + joblist[jobid].job_salary + '</span>';
		html += '<div class="chat_yx_com_name">' + joblist[jobid].com_name + '</div>';
		html += '<div class="">' + joblist[jobid].job_city_one;
		if(joblist[jobid].job_city_two){
			html += '-' + joblist[jobid].job_city_two;
		}
		if(joblist[jobid].job_exp){
			html += ' . ' + joblist[jobid].job_exp+'经验';
		}
		if(joblist[jobid].job_edu){
			html += ' . ' + joblist[jobid].job_edu+'学历';
		}
		html += '</div>';
		if(msg && msg.newjob){
			var msgtime = parseInt(msg.msgtime);
			var gtuser;
			if(msg.newjob == 1){
				gtuser = '你';
			}else{
				if(msg.fusertype == 1){
					if(mine.usertype == 1){
						gtuser = '你';
					}else{
						gtuser = '招聘者';
					}
				}else{
					if(mine.usertype == 1){
						gtuser = '求职者';
					}else{
						gtuser = '你';
					}
				}
			}
			html += '<div class="chat_yx_time">' + timeFormat(msgtime) + ' 由' + gtuser + '发起的沟通</div></span></div></li>';
		}
		html += '</li>';
	}
	return html;
}
function getResumeHtml(eid){
	var html = '';
	if(expect){
		html = '<li class="chat_li"><div class="chat_userresume" data-wapurl="' + expect.weburl + '" onclick="toShow(this)">';
		html += '<span><div class="chat_userresume_name">' + expect.uname + ' <span class="chat_userresume_ys">' + expect.sex_n + ',' + expect.age + '岁</span></div>';
		html += '<div class="chat_userresume_info">' + expect.exp_n + ' . ' + expect.edu_n + ' </div>';
		html += '<div class="chat_userresume_want">期望职位 <span class="chat_userresume_wantjob">' + expect.name +'</span> </div>';
		html += '<div class="chat_userresume_pic"><img src=" ' + expect.photo + ' "></div></span></div></li>';
	}
	return html;
}
// 转义内容
function rexContent(content){
	content = (content||'').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;') //XSS
	.replace(/img\[([^\s]+?)\]/g, function(img){  //转义图片
      return '<img class="chat_photos" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
    })
	return content;
}
function upImage(obj){
	$('#imgform').submit();
	var iframe = $('#chat_iframe'), timer = setInterval(function() {
		var res;
		try {
			res = iframe.contents().find('body').text();
		} catch(e) {
			clearInterval(timer);
		}
		if(res){
			clearInterval(timer);
			iframe.contents().find('body').html('');
			try {
				res = JSON.parse(res);
			} catch(e){
				res = {};
			}
			if (res.msg){
				layer.msg(res.msg,2,8);
			}else{
				focusInsert(document.getElementById("send_content"), 'img['+ (res.data.url||'') +']', true);
				send();
			}
			
		}
    }, 30);
    obj.value = '';
}
function timeFormat(nowtime) {
	if(nowtime){
		nowtime = new Date(nowtime);
	}else{
		nowtime = new Date();
	}
	var month = nowtime.getMonth(),
		day = nowtime.getDate(),
		hour = nowtime.getHours(),
		minutes = nowtime.getMinutes();
	month = month + 1;
	if (month < 10) {
		month = '0' + month;
	}
	if (hour < 10 && hour > 0) {
		hour = '0' + hour;
	}
	if (minutes < 10 && minutes > 0) {
		minutes = '0' + minutes;
	}
	if (day < 10 && day > 0) {
		day = '0' + day;
	}
	var time = month + '-' + day + ' ' + hour + ':' + minutes;
	return time;
}
// 页面滚动
function chatScrollTo(ypos) {
	var clientHeight = document.getElementById('chat_box').clientHeight;;
	if(ypos > clientHeight){
		// 兼容各种浏览器
		document.getElementById('chat_box').scrollTop = ypos;
	}
}
//在焦点处插入内容
function focusInsert(obj, str, nofocus){
    var result, val = obj.value;
    nofocus || obj.focus();
    if(document.selection){ //ie
		result = document.selection.createRange(); 
		document.selection.empty(); 
		result.text = str; 
    } else {
		result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
		nofocus || obj.focus();
		obj.value = result.join('');
    }
}
//查看更多记录
function chatListMore(){
    var chatMain = $('#chat_content');
    var ul = chatMain.find('ul'), li = ul.children('.chat_li'); 
    
    if(li.length >= MAX_ITEM){
      var first = li.eq(0);
      first.prev().remove();
      if(!ul.prev().hasClass('chat_more')){
        ul.before('<li id="chat_more" class="chat_more" onclick="moreChat()"><div class="chat_comjobtip"><span class="chat_comjobtip_p">查看更多记录</span></div></li>');
      }
      first.remove();
    }
    chatMain.scrollTop(chatMain[0].scrollHeight + 1000);
}
function moreChat(){
	$.ajax({
		type : "post",
		url : weburl + "/index.php?m=chat&c=getChatPage",
		async: false,
		data : {'id': toid,'totype': totype,'page': page},
		dataType : "json",
		success : function(res) {
			if (res) {
				//准备数据
				var pint = setInterval(function(){
						if(mine.id){
							clearInterval(pint);
							prepare();
						}
					},100);
				page = page + 1;
				var scroll = null;
				if(page > 2){
					// 第二页开始，记录前一次滚动距离
					scroll = document.getElementById('chat_content').scrollHeight;
				}
				
				$('#chat_more').remove();
				if(res.code == 0){
					var chatlog = res.data;
					if(chatlog.length > 0){
						pastSend = chatlog[0].sendTime;
						for(var i in chatlog){
							renderPast(chatlog[i]);
							// 最后一条时，如还有历史消息，增加更多消息
							if(i == chatlog.length -1 && res.ismore){
								$("#chat_content").find('ul').prepend('<li id="chat_more" class="chat_more" onclick="moreChat()"><div class="chat_comjobtip"><span class="chat_comjobtip_p">查看更多记录</span></div></li>');
							}
							if(scroll){
								// 渲染后，滚动到上一页的距离
								var newScroll = document.getElementById('chat_content').scrollHeight;
								chatScrollTo(newScroll - scroll);
							}
						}
					}
				}
			}
		}
    });
}
// 渲染历史消息
function renderPast(msg){
	// 接收
	if(msg.msgtype == 'char'){
		msg.content = rexContent(msg.content);
		if(msg.mine){
			// 我说
			var html  = '<li class="chat_li"><div class="chat_sendcont">';
				html += '<div class="chat_sendcont_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p">' + msg.content + '</span></div></li>';
		}else{
			// 他说
			var html = '<li class="chat_li"><div class="chat_other_say">';
				html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
				html += '<span class="chat_sendcont_p2">' + msg.content + '</span></div></li>';
		}
	}else{
		if(msg.msgtype == 'job'){
			if(msg.content.indexOf('jobid') != -1){
				var jobid = msg.content.replace('jobid=','');
				var html = getJobHtml(jobid, msg);
				if(jid==''){
					showChatJob(jobid);
				}
				jid = jobid;
				jobShowed = false;
			}
		}else if(msg.msgtype == 'resume'){
			if(msg.content.indexOf('eid') != -1){
				var eid = msg.content.replace('eid=','');
				var html = getResumeHtml(eid);
			}
		}else if(msg.msgtype == 'change'){
			if (mine.usertype == 1) {
				var change = '求职者更换了与您沟通的职位';
			} else {
				var change = '招聘者更换了与您沟通的职位';
			}
			var html = '<li class="chat_li"><div class="chat_comjobtip"><span class="chat_comjobtip_p">' + change + '</span></div></li>';
		}else if(msg.msgtype == 'invite'){
			if(msg.content.indexOf('inviteid') != -1){
				var qyid = msg.content.replace('inviteid=','');
				if(msg.mine){
					var html = '<li class="chat_li"><div class="chat_sendcont">';
					html += '<div class="chat_sendcont_pic"><img src="' + mine.avatar + '"></div>';
					html += '<span class="chat_sendcont_p"><em class="chat_sendcont_yqbox">发送了面试邀请<i class="chat_sendcont_yq"></i></em></span></div></li>';
				}else{
					var html = '<li class="chat_li"><div class="chat_other_say">';
					html += '<div class="chat_other_pic"><img src="' + msg.avatar + '"></div>';
					html += '<span class="chat_sendcont_p2"><em class="chat_sendcont_jsbox">发送了面试邀请<i class="chat_sendcont_jsyq"></i></em></span></div></li>';
				}
				if(inviteid !='' && inviteid == qyid){
					inviteid = '';
				}
			}
		}else{
			var html = msg.content;
		}
	}
	$("#chat_content").find('ul').prepend(html);
	// 消息时间间隔超60秒，显示新时间
	if(pastSend - msg.sendTime > 60*1000){
		$("#chat_content").find('ul').prepend('<li class="chat_li"><div class="chat_sendtime">' + timeFormat(parseInt(msg.sendTime)) + '</div></li>');
		pastSend = msg.sendTime;
	}
	if(page == 2){
		var scroll = document.getElementById('chat_content').scrollHeight;
		chatScrollTo(scroll);
		// 图片类型加载较慢，滚动到底部需要时间
		var timer_num = 0;
		var timer = setInterval(function() {
			timer_num++;
			var imgscroll = document.getElementById('chat_content').scrollHeight;
			chatScrollTo(imgscroll);
			if(timer_num > 20){
				clearInterval(timer);
			}
		}, 50);
	}
}
function showChatJob(id){
	var html = '';
	if($('#content_job')){
		if(joblist && joblist[id]){
			html += '<span class="chat_box_right_gtjob_n">沟通职位</span><a href="'+ joblist[id].weburl +'" target="_blank" class="chat_box_right_gtjob_name">' + joblist[id].name + '</a>';
			html += '<span class="chat_box_right_gtjob_xz">' + joblist[id].job_salary + '</span>' + joblist[id].job_city_one;
			
			if(joblist[id].job_city_two){
				html += '-' + joblist[id].job_city_two;
			}
			$('#content_job').html(html);
		}
	}
}
// 对方未在线，发送提醒
function unSend(msg){
	$.post(weburl + "/index.php?m=chat&c=unSend", {
		'nowtype': msg.ftype,
		'toid': msg.toid,
		'totype': msg.totype
	}, function() {});
}
/* 会员中心判断聊天权利*/
function toChat(id,type,nowtype){
	
	if(nowtype != 1){
		loadlayer();
		$.post("index.php?c=chat&act=chatRight",{chatid:id},function(data){
			layer.closeAll('loading');
			var data	=	eval('('+data+')');
			
			var status	=	data.status;
			
			if(status == 1){	//	可以聊天
				
				window.location.href = 'index.php?c=chat&id=' + id + '&type=' + type;
				
			}else if(status == 2){	//	购买服务
					
				$('#chatid').val(id);
				server_single('chat');
			
				var msglayer = layer.open({
					type: 1,
					title: chat_name,
					closeBtn: 1,
					border: [10, 0.3, '#000', true],
					area: ['810px', 'auto'],
					content: $("#tcmsg"),
					cancel:function(){
						window.location.reload();
					}
				});
			
				 
			}else{
				
				layer.msg(data.msg , 2, 8);return false;
			}
		});	
	}else{
		window.location.href = 'index.php?c=chat&id=' + id + '&type=' + type;
	}
}